<template>
  <div>

    <el-upload

      list-type="picture-card"
      :limit="1"
      action="#"
      :http-request="uploads"
      :file-list="filelist"
      :before-upload="beforeUpload"
      :on-remove="beforeRemove"
      :on-preview="handlePictureCardPreview"
      :class="{disable :filelist.length>0}"
      :on-change="onChange"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showprog" :percentage="prog" status="success" style="width:200px " />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import Cos from 'cos-js-sdk-v5'
export default {
  data() {
    return {
      filelist: [],
      dialogImageUrl: '',
      dialogVisible: false,
      showprog: false,
      prog: 10
    }
  },

  methods: {

    beforeUpload(i) {
      const arr = ['image/jpeg', 'image/png']
      const a = 500 * 1024
      if (!arr.includes(i.type)) {
        this.$message.error('文件类型不符合·')
        return false
      }
      if (i.size > a) {
        this.$message.error('文件太大了')
        return false
      }
    },
    beforeRemove(a, b) {
      this.filelist = [...b]
    },
    onChange(a, b) {
      this.filelist = [...b]
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    uploads(v) {
      this.showprog = true
      console.log(v)
      const cos = new Cos({
        SecretId: 'AKIDpTryoOhkW1GEuJSJtCF0UgbFdkZ8QREq', // 身份识别 ID
        SecretKey: 'OXQ4SbU7VeXAZibEbjbDZgX8TaQzIJCo' // 身份密钥
      })
      cos.putObject({
        Bucket: 'rz-1306247071', /* 必须 */
        Region: 'ap-guangzhou', /* 必须 */
        Key: v.file.name, /* 必须 */
        Body: v.file,
        StorageClass: 'STANDARD',
        onProgress: (progressData) => {
          const aa = progressData
          console.log(aa.percent)
          this.prog = aa.percent * 100
        }
      }, (err, data) => {
        // console.log(err || data)
        if (!err) {
          console.log(data)
          this.showprog = false
          this.filelist[0].url = 'http://' + data.Location
          console.log(this.filelist)
          this.filelist[0].status = 'success'
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
// /deep/ img {
::v-deep img {
  object-fit: contain;
}

.disable  {
  // /deep/ .el-upload--picture-card {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
